package cn.yunhe.dao;

import cn.yunhe.pojo.News;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class NewsDaoImpl extends HibernateDaoSupport implements NewsDao {
    @Override
    public List<News> getAllNews() {
        return getHibernateTemplate().find("from News");
    }

    @Override
    public List<News> getNews(final News news) {
        List<News> list = getHibernateTemplate().executeFind( new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(News.class);
                if(news != null){
                    if(news.getTitle()!=null){
                        criteria.add(Restrictions.like("title",news.getTitle(),MatchMode.ANYWHERE));
                    }if(news.getBoardId()>0){
                        criteria.add(Restrictions.eq("boardId",news.getBoardId()));
                    }
                }
                return  criteria.list();
            }
        });

        return list;
    }
}
